﻿using MQTTnet.Client;
using MQTTnet;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading.Tasks;
using MQTTnet.Packets;
using System.Text;
using RtspControl;

namespace 云起停车_岗亭端
{
    public partial class Form2 : Form
    {
        // 静态常量定义字体大小
        private static readonly int FontSizeLarge = 14;
        private static readonly int FontSizeMedium = 12;
        private static readonly int FontSizeSmall = 10;
        private static readonly int FontSizeMini = 9;
        private int FontSize = FontSizeMedium; // 默认字体大小

        private TableLayoutPanel videoPanel;
        private Panel recordPanel;
        private FlowLayoutPanel recordListView;
        private MenuStrip menuStrip;
        private Label noRecordsLabel; // “暂无记录”标签
        private Splitter splitter; // 分隔条
        private Timer timer=null;

        private static Form2 form2 = null; // 单例实例
        private Queue<JObject> queue = new Queue<JObject>();
        private static int maxLogs = 1000;
        private static JObject update = null;
        private MqttConfig mqttConfig = null; // MQTT配置
        private Barrier[] barriers = null; // 停车场道闸列表
        private string[] tips=null;
        private int hide_window = 0;


        private Form2()
        {
            InitializeComponent();
            InitializeUI();
        }

        public static Form2 getInstance()
        {
            if (form2 != null)
            {
                return form2;
            }
            form2= new Form2();
            return form2;
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            Form1 form1= Form1.getInstance();
            form1.Show();
        }

        private void showUpdate()
        {
            string version = RtspPlayer.Properties.Settings.Default.版本号;
            string download = RtspPlayer.Properties.Settings.Default.下载地址;
            string last_version = "";
            bool force_update = false;
            foreach (var item in update) {
                last_version = item.Key;
                if (item.Key.Equals(version))
                {
                    force_update = (bool)item.Value;
                }
            }
            if (version.Equals(last_version))
            {
                MessageBox.Show("已经是最新版本");
                return;
            }
            Update form = new Update(version, last_version, force_update,download);
            form.ShowDialog();
        }

        private bool fomateConfig(JObject config)
        {
            this.Text = (string)config.GetValue("title");
            update = (JObject)config.GetValue("update");
            string version = RtspPlayer.Properties.Settings.Default.版本号;
            if (!update.ContainsKey(version))
            {
                this.showUpdate();
                return false;
            }
            if ((bool)update.GetValue(version)) {
                this.showUpdate();
                return false;
            }
            JObject mqtt = (JObject)config.GetValue("mqttConfig");
            JArray array = (JArray)config.GetValue("screen");
            //将mqttConfig转换为MqttConfig对象
            this.mqttConfig= mqtt.ToObject<MqttConfig>();
            this.barriers=new Barrier[array.Count];
            int i = 0;
            foreach(JObject obj in array)
            {
                //将每个道闸对象转换为Barrier对象
                Barrier barrier = obj.ToObject<Barrier>();
                JArray fujis=(JArray)obj.GetValue("fuji");
                barrier.childs = null;
                if (fujis.Count>0){
                    barrier.childs= new Barrier[fujis.Count];
                    int j = 0;
                    foreach (JObject fobj in fujis)
                    {
                        barrier.childs[j] = fobj.ToObject<Barrier>();
                        j++;
                    }
                }
                barrier.rtsp = new RtspControl.VideoControl()
                {
                    Visible =false,
                    Name = barrier.serialno + "_rtsp"
                };
                this.barriers[i] = barrier;
                i++;
            }
            //将tips转换为string数组
            JToken jtoken=config.GetValue("tips");
            if (jtoken == null || jtoken.Type == JTokenType.Null)
            {
                this.tips = new string[] { };
            }
            else
            {
                JArray tips = (JArray)jtoken;
                this.tips = new string[tips.Count];
                for (int j = 0; j < tips.Count; j++)
                {
                    this.tips[j] = (string)((JObject)tips[j]).GetValue("remark");
                }
            }
            this.hide_window= (int)config.GetValue("hide_window");

            return true;
        }

        private void MqttConnet() 
        {
            // 创建 MQTT 客户端
            var factory = new MqttFactory();
            var mqttClient = factory.CreateMqttClient();

            string mqtt_host = mqttConfig.mqtt_host;
            int mqtt_port = mqttConfig.mqtt_port;
            string mqtt_username = mqttConfig.mqtt_username;
            string mqtt_password = mqttConfig.mqtt_password;
            string clientId = mqttConfig.mqtt_client_id;
            // 配置 MQTT 客户端选项
            var options = new MqttClientOptionsBuilder()
                .WithTimeout(TimeSpan.FromSeconds(4))
                .WithClientId(clientId)
                .WithCredentials(mqtt_username, mqtt_password)
                .WithTcpServer(mqtt_host, mqtt_port)
                .WithCleanSession()
                .Build();
            //处理连接成功事件
            mqttClient.ConnectedAsync += e =>
            {
                Console.WriteLine("MQTT Connected");
                foreach (Barrier video in this.barriers)
                {
                    string serialno = video.serialno;
                    int parking_id = video.parking_id;
                    string topic = serialno + "/barrier/screen/record/message/" + parking_id;
                    MqttTopicFilter filter = new MqttTopicFilterBuilder().WithTopic(topic).WithAtLeastOnceQoS().Build();
                    mqttClient.SubscribeAsync(filter);
                }
                return Task.CompletedTask;
            };
            //处理接收消息事件
            mqttClient.ApplicationMessageReceivedAsync += e => {
                string topic = e.ApplicationMessage.Topic;
                ArraySegment<byte> segment = e.ApplicationMessage.PayloadSegment;
                string fulldata = Encoding.UTF8.GetString(segment.Array, segment.Offset, segment.Count);
                Console.WriteLine($"收到主题: {topic}");
                Console.WriteLine($"消息内容: {fulldata}");
                // 解析消息内容
                JObject msgobj= JObject.Parse(fulldata);
                if (!msgobj.ContainsKey("payload")) {
                    return null;
                }
                JObject payload = (JObject)msgobj.GetValue("payload");
                if (!payload.ContainsKey("body"))
                {
                    return null;
                }
                JObject body = (JObject)payload.GetValue("body");
                if (!body.ContainsKey("type"))
                {
                    return null;
                }
                this.queue.Enqueue(body);
                return Task.CompletedTask;
            };
            //处理断开连接事件
            mqttClient.DisconnectedAsync += e =>
            {
                Console.WriteLine("MQTT Disconnected");
                Task.Delay(5000);
                mqttClient.ConnectAsync(options);
                return Task.CompletedTask;
            };
            //连接到 MQTT Broker
            mqttClient.ConnectAsync(options);
        }

        private async void Form2_Load(object sender, EventArgs e)
        {
            Response response = await Utils.GetAsync("sentrybox/index/client");
            if (null == response)
            {
                return;
            }
            JObject config = (JObject)response.data;
            Console.WriteLine(config.ToString());
            // 解析配置文件
            bool success = this.fomateConfig(config);
            if (success)
            {
                this.MqttConnet();
                this.InitForm3();
                this.InitializeVideos();
            }
        }

        private void InitForm3()
        { 
            foreach(Barrier barrier in this.barriers)
            {
               Form3 form3 = Form3.getInstance(barrier,this.FontSize,this.hide_window);
               form3.SetOptions(this.tips);
            }
        }

        private void InitializeUI()
        {
            // 窗体设置
            this.WindowState = FormWindowState.Maximized;
            // 视频监控区域
            videoPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.LightGray,
            };
            this.Controls.Add(videoPanel);

            // 通道记录栏
            recordPanel = new Panel
            {
                Dock = DockStyle.Right,
                Width = 350,
                BackColor = Color.LightGray,
                Padding = new Padding(0, 3, 3, 3)
            };
            // 添加标题
            var recordTitle = new Label
            {
                Text = "通道即时记录",
                Dock = DockStyle.Top,
                Font = new Font("Microsoft YaHei", FontSize, FontStyle.Bold),
                TextAlign = ContentAlignment.MiddleCenter,
                Name = "recordTitle",
                BackColor = Color.LightBlue
            };
            // 初始化“暂无记录”标签
            noRecordsLabel = new Label
            {
                Text = "😢暂无记录！",
                Dock = DockStyle.Fill,
                Font = new Font("Microsoft YaHei", FontSize),
                TextAlign = ContentAlignment.MiddleCenter,
                ForeColor = Color.Gray,
                BackColor = Color.White,
                Visible = true
            };
            recordListView = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                Width = recordPanel.Width,
                BackColor = Color.White,
                FlowDirection = FlowDirection.TopDown,
                WrapContents = false,
                Visible = false
            };
            recordPanel.Controls.Add(noRecordsLabel);
            recordPanel.Controls.Add(recordListView);
            recordPanel.Controls.Add(recordTitle);
            // 添加 Splitter 控件
            splitter = new Splitter
            {
                Dock = DockStyle.Right, // 与 recordPanel 的 DockStyle 保持一致
                Width = 3, // 分隔条的宽度
                BackColor = Color.White, // 分隔条的颜色
            };
            splitter.SplitterMoved += Splitter_SplitterMoved;
            // 将控件添加到窗体
            this.Controls.Add(splitter);
            this.Controls.Add(recordPanel);

            // 菜单栏
            menuStrip = new MenuStrip();

            // 清除记录菜单
            var refreshVideo = new ToolStripMenuItem("刷新监控视频");
            refreshVideo.Click += RefreshVideo;
            menuStrip.Items.Add(refreshVideo);
            // 关闭锁屏菜单
            var closeLockScreenMenu = new ToolStripMenuItem("离开关闭锁屏");
            closeLockScreenMenu.Click += CloseLockScreen;
            // 清除记录菜单
            var clearRecordsMenu = new ToolStripMenuItem("清除通道记录");
            clearRecordsMenu.Click += ClearRecords;
            // 设置记录栏位置菜单
            var setRecordPanelPositionMenu = new ToolStripMenuItem("通道记录位置");
            // 添加子菜单项
            var topMenuItem = new ToolStripMenuItem("顶部", null, (s, e) => SetRecordPanelDock(DockStyle.Top));
            var bottomMenuItem = new ToolStripMenuItem("底部", null, (s, e) => SetRecordPanelDock(DockStyle.Bottom));
            var leftMenuItem = new ToolStripMenuItem("左侧", null, (s, e) => SetRecordPanelDock(DockStyle.Left));
            var rightMenuItem = new ToolStripMenuItem("右侧", null, (s, e) => SetRecordPanelDock(DockStyle.Right));
            // 将子菜单项添加到“设置记录栏位置”菜单
            setRecordPanelPositionMenu.DropDownItems.Add(topMenuItem);
            setRecordPanelPositionMenu.DropDownItems.Add(bottomMenuItem);
            setRecordPanelPositionMenu.DropDownItems.Add(leftMenuItem);
            setRecordPanelPositionMenu.DropDownItems.Add(rightMenuItem);
            // 设置字体大小菜单
            var setFontSizeMenu = new ToolStripMenuItem("设置字体大小");
            setFontSizeMenu.DropDownItems.Add("大", null, (s, e) => ChangeFontSize(FontSizeLarge));
            setFontSizeMenu.DropDownItems.Add("中", null, (s, e) => ChangeFontSize(FontSizeMedium));
            setFontSizeMenu.DropDownItems.Add("小", null, (s, e) => ChangeFontSize(FontSizeSmall));
            setFontSizeMenu.DropDownItems.Add("极小", null, (s, e) => ChangeFontSize(FontSizeMini));
            // 检查更新
            var updateAppMenu = new ToolStripMenuItem("检查系统更新");
            updateAppMenu.Click += UpdateApp;

            // 将菜单项添加到菜单栏
            menuStrip.Items.Add(closeLockScreenMenu);
            menuStrip.Items.Add(clearRecordsMenu);
            menuStrip.Items.Add(setRecordPanelPositionMenu);
            menuStrip.Items.Add(setFontSizeMenu);
            menuStrip.Items.Add(updateAppMenu);

            this.MainMenuStrip = menuStrip;
            this.Controls.Add(menuStrip);
            //初始化字体
            ChangeControlFont(recordPanel, FontSizeMedium);
            ChangeControlFont(menuStrip, FontSizeMedium);
            //初始化定时器
            this.timer = new Timer();
            this.timer.Interval = 200;
            //绑定定时器事件
            this.timer.Tick += timer_Tick;
            this.timer.Start();
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            // 定时器事件处理逻辑
            if (queue.Count > 0)
            {
                if (this.noRecordsLabel.Visible)
                {
                    this.noRecordsLabel.Visible = false;
                }
                if (!this.recordListView.Visible) {
                    this.recordListView.Visible = true;
                }
                JObject body = queue.Dequeue();
                string msgtype = (string)body.GetValue("type");
                string message = (string)body.GetValue("message");
                string colorname = (string)body.GetValue("color");
                Color textColor = Color.FromName(colorname);
                string imageUrl = null;
                if (msgtype.Equals("message"))
                {
                    //正则表达式匹配图片
                    string pattern = @"<br><img .*?/><br>";
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
                    System.Text.RegularExpressions.MatchCollection matches = regex.Matches(message);
                    if (matches.Count > 0)
                    {
                        // 获取第一个匹配的图片
                        string imgpath = matches[0].Value;
                        // 提取图片的 src 属性
                        int startIndex = imgpath.IndexOf("src=\"") + 5;
                        int endIndex = imgpath.IndexOf("\"", startIndex);
                        imageUrl = imgpath.Substring(startIndex, endIndex - startIndex);
                        //message去掉<br><img .*?/><br>
                        message = message.Replace(matches[0].Value, "");
                    }
                    if (message.IndexOf("支付成功")!=-1)
                    {
                        int startIndex = message.IndexOf("】") + 1;
                        int endIndex = message.IndexOf("，");
                        string plate_number = message.Substring(startIndex, endIndex - startIndex);
                        Form3.CloseFormByPlatenumber(plate_number);
                    }
                }
                if (msgtype.Equals("pay") || msgtype.Equals("manual") || msgtype.Equals("recovery"))
                {
                    int barrier_id = (int)body.GetValue("barrier_id");
                    string photo = (string)body.GetValue("photo");
                    Barrier barrier = null;
                    try 
                    {
                        barrier = Barrier.getBarrierById(this.barriers, barrier_id);
                    }catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        return;
                    }
                    string plate_number = (string)body.GetValue("plate_number");
                    Form3.CloseFormByPlatenumber(plate_number);
                    Form3 form3 = Form3.getInstance(barrier,this.FontSize, this.hide_window);
                    form3.SetMessage(message);
                    form3.SetPlateNumber(plate_number);
                    if (msgtype.Equals("pay")) 
                    { 
                        form3.SetRecordsId((int)body.GetValue("records_id"));
                    }
                    if (msgtype.Equals("recovery"))
                    {
                        form3.SetRecoveryId((int)body.GetValue("recovery_id"));
                    }
                    if (msgtype.Equals("manual"))
                    {
                        form3.SetTriggerId((int)body.GetValue("trigger_id"));
                    }
                    form3.Display(msgtype, photo);
                }
                this.AddLog(message, textColor, imageUrl);
            }
        }


        private async void AddLog(string text, Color textColor, string imgpath=null)
        {
            // 删除最旧的日志
            if (this.recordListView.Controls.Count >= maxLogs)
            {
                this.recordListView.Controls.RemoveAt(this.recordListView.Controls.Count - 1);
            }
            // 添加文本
            Label logLabel = new Label
            {
                Text = text,
                ForeColor = textColor,
                Dock = DockStyle.Left,
                AutoSize = true,
                Margin = new Padding(0, 10, 0, 0),
            };
            this.recordListView.Controls.Add(logLabel);
            this.recordListView.Controls.SetChildIndex(logLabel, 0);
            // 添加图片
            if (imgpath != null)
            {
                Image image = await Utils.LoadImageFromUrlAsync(imgpath);
                int width = image.Width;
                int height = image.Height;
                int newwidth = this.recordListView.Width > 350 ? 350 : this.recordListView.Width;
                //等比例缩小高度
                int newheight = (int)(height * ((float)newwidth / width));
                PictureBox pictureBox = new PictureBox
                {
                    Image = image,
                    SizeMode = PictureBoxSizeMode.StretchImage,
                    Dock = DockStyle.Left,
                    Width = newwidth,
                    Height = newheight,
                    Margin = new Padding(0, 10, 0, 0),
                };
                this.recordListView.Controls.Add(pictureBox);
                this.recordListView.Controls.SetChildIndex(pictureBox, 1);
            }
            // 滚动到顶部
            this.recordListView.VerticalScroll.Value = 0;
        }
        private void Splitter_SplitterMoved(object sender, SplitterEventArgs e)
        {
            // 确保 recordPanel 的宽度或高度在合理范围内
            if (recordPanel.Dock == DockStyle.Right || recordPanel.Dock == DockStyle.Left)
            {
                // 限制宽度
                if (recordPanel.Width < 100)
                {
                    recordPanel.Width = 100; // 最小宽度
                }
                else if (recordPanel.Width > this.ClientSize.Width - 100)
                {
                    recordPanel.Width = this.ClientSize.Width - 100; // 最大宽度
                }
            }
            else if (recordPanel.Dock == DockStyle.Top || recordPanel.Dock == DockStyle.Bottom)
            {
                // 限制高度
                if (recordPanel.Height < 100)
                {
                    recordPanel.Height = 100; // 最小高度
                }
                else if (recordPanel.Height > this.ClientSize.Height - 100)
                {
                    recordPanel.Height = this.ClientSize.Height - 100; // 最大高度
                }
            }
            this.RefreshVideo(null, null);
        }

        // 刷新视频监控
        private void RefreshVideo(object sender, EventArgs e)
        {
            foreach(Barrier video in this.barriers)
            {
                video.rtsp.Visible = false;
                video.rtsp.Stop();
            }
            System.Threading.Thread.Sleep(1000);
            foreach (Barrier video in this.barriers)
            {
                string url = video.url;
                if (this.FontSize == FontSizeMini || this.FontSize == FontSizeSmall)
                {
                    video.rtsp.Height = videoPanel.Height / videoPanel.RowCount - 37;
                }
                else
                {
                    video.rtsp.Height = videoPanel.Height / videoPanel.RowCount - 45;
                }
                video.rtsp.Width = videoPanel.Width / videoPanel.ColumnCount;
                video.rtsp.Visible = true;
                video.rtsp.StartPlay(url);
            }
        }

        // 播放视频的逻辑
        private void InitializeVideos()
        {
            if (this.barriers.Length == 2)
            {
                // 特殊处理：当视频数为 2 时，两个视频在同一行，recordPanel 在底部
                ConfigureVideoPanelLayout(1, 2, new[] { 100f }, new[] { 50f, 50f });

                // 添加两个视频容器
                foreach (Barrier video in this.barriers)
                {
                    AddVideoContainer(video);
                }
                // 将 recordPanel 放置在底部
                SetRecordPanelDock(DockStyle.Bottom);
            }
            else
            {
                int rows = (int)Math.Ceiling(Math.Sqrt(this.barriers.Length));
                int cols = (int)Math.Ceiling((double)this.barriers.Length / rows);

                ConfigureVideoPanelLayout(rows, cols, GenerateEqualPercentages(rows), GenerateEqualPercentages(cols));

                foreach (Barrier video in this.barriers)
                {
                    AddVideoContainer(video);
                }
            }
            ChangeControlFont(videoPanel, FontSizeMedium);
            this.RefreshVideo(null,null);
        }
        // 配置 videoPanel 的布局
        private void ConfigureVideoPanelLayout(int rows, int cols, float[] rowPercentages, float[] colPercentages)
        {
            videoPanel.RowCount = rows;
            videoPanel.ColumnCount = cols;
            videoPanel.RowStyles.Clear();
            videoPanel.ColumnStyles.Clear();

            foreach (float percentage in rowPercentages)
            {
                videoPanel.RowStyles.Add(new RowStyle(SizeType.Percent, percentage));
            }

            foreach (float percentage in colPercentages)
            {
                videoPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percentage));
            }
        }
        // 添加视频容器
        private void AddVideoContainer(Barrier video)
        {
            string title = video.title;
            string serialno = video.serialno;
            string barrier_type = video.barrier_type;

            var videoContainer = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.DarkGray,
                BorderStyle = BorderStyle.FixedSingle,
                Name = serialno,
            };

            // 添加视频标题
            var videoTitle = new Label
            {
                Text = title,
                Dock = DockStyle.Top,
                Font = new Font("Microsoft YaHei", FontSize, FontStyle.Bold),
                TextAlign = ContentAlignment.MiddleCenter,
                Height = 25,
                BackColor = Color.LightBlue
            };
            videoContainer.Controls.Add(videoTitle);
            // 添加视频流控件
            videoContainer.Controls.Add(video.rtsp);
            // 添加按钮面板
            var buttonPanel = CreateButtonPanel(videoContainer, barrier_type);
            videoContainer.Controls.Add(buttonPanel);
            videoPanel.Controls.Add(videoContainer);
        }
        // 创建按钮面板
        private FlowLayoutPanel CreateButtonPanel(Panel videoContainer, string barrier_type)
        {
            var buttonPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Bottom,
                BackColor = Color.White,
                Name = "buttonPanel",
            };
            //为buttonPanel设置一个标志
            Button enterExitButton = null;
            if (barrier_type.Equals("entry")) {
                 enterExitButton = new Button { Text = "入场", BackColor = Color.LightGreen };
                 // 处理入场
                 enterExitButton.Click += (s, e) => ToggleEntry(videoContainer, enterExitButton);
            }
            if (barrier_type.Equals("exit"))
            {
                enterExitButton = new Button { Text = "出场", BackColor = Color.LightGreen };
                // 处理出场
                enterExitButton.Click += (s, e) => ToggleExit(videoContainer, enterExitButton);
            }
            var triggerButton = new Button { Text = "识别",BackColor = Color.LightBlue };
            var openGateButton = new Button { Text = "开闸",BackColor = Color.LightYellow };
            var closeGateButton = new Button { Text = "关闸",BackColor = Color.LightCoral };
            var expandGateButton = new Button { Text = "放大",BackColor = Color.LightSalmon };
            // 识别处理
            triggerButton.Click += (s, e) => ToggleTrigger(videoContainer, triggerButton);
            // 开闸处理
            openGateButton.Click += (s, e) => ToggleOpenGate(videoContainer, openGateButton);
            // 关闸处理
            closeGateButton.Click += (s, e) => ToggleCloseGate(videoContainer, closeGateButton);
            // 添加“放大”按钮的点击事件
            expandGateButton.Click += (s, e) => ToggleVideoExpand(videoContainer, expandGateButton);

            buttonPanel.Controls.Add(enterExitButton);
            buttonPanel.Controls.Add(triggerButton);
            buttonPanel.Controls.Add(openGateButton);
            buttonPanel.Controls.Add(closeGateButton);
            buttonPanel.Controls.Add(expandGateButton);

            return buttonPanel;
        }

        private void ToggleEntry(Panel videoContainer, Button button)
        {
            Barrier barrier = Barrier.getBarrierBySerialNo(this.barriers, videoContainer.Name);
            PlateNumber plateNumber = new PlateNumber(barrier);
            plateNumber.ShowDialog();
        }

        private void ToggleExit(Panel videoContainer, Button button)
        {
            Barrier barrier = Barrier.getBarrierBySerialNo(this.barriers, videoContainer.Name);
            PlateNumber plateNumber = new PlateNumber(barrier);
            plateNumber.ShowDialog();
        } 

        private async void ToggleTrigger(Panel videoContainer, Button button)
        {
            Barrier barrier=Barrier.getBarrierBySerialNo(this.barriers, videoContainer.Name);
            JObject obj = new JObject();
            obj.Add("barrier_id", barrier.id);
            await Utils.PostAsync("sentrybox/index/trigger", obj, this);
        } 
        
        private async void ToggleCloseGate(Panel videoContainer, Button button)
        {
            Barrier barrier=Barrier.getBarrierBySerialNo(this.barriers, videoContainer.Name);
            // 显示包含确定和取消按钮的消息框
            DialogResult result = MessageBox.Show("您确定要关闭"+ barrier.title+ "吗？", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                JObject obj = new JObject();
                obj.Add("barrier_id", barrier.id);
                await Utils.PostAsync("sentrybox/index/close", obj, this);
            }
        } 
        
        private async void ToggleOpenGate(Panel videoContainer, Button button)
        {
            Barrier barrier=Barrier.getBarrierBySerialNo(this.barriers, videoContainer.Name);
            JObject obj = new JObject();
            obj.Add("barrier_id", barrier.id);
            Response response = await Utils.PostAsync("sentrybox/index/photo", obj, this);
            if (null == response)
            {
                return;
            }
            JObject rdata=(JObject)response.data;
            string photo = (string)rdata.GetValue("photo");
            bool isplate = (bool)rdata.GetValue("isplate");
            string plate_number = (string)rdata.GetValue("plate_number");
            string plate_type = (string)rdata.GetValue("plate_type");
            string msg = "未检测到车辆";
            if (isplate && !plate_number.Equals(""))
            {
                Dictionary<string, string> color = new Dictionary<string, string>() {
                    {"blue","蓝色"},
                    {"green","绿色"},
                    {"yellow","黄色"},
                    {"black","黑色"},
                    {"white","白色"}  
                };
                msg ="检测到车辆，车牌号："+ plate_number+ "，车牌颜色：" + color[plate_type];
            }
            if (isplate && plate_number.Equals(""))
            {
                msg = "检测到无牌车";
            }
            Form3 form3 = Form3.getInstance(barrier, this.FontSize, this.hide_window);
            form3.SetMessage(msg);
            form3.SetPlateNumber(plate_number);
            form3.Display("open", photo);
        }

        // 生成等比例的百分比数组
        private float[] GenerateEqualPercentages(int count)
        {
            float percentage = 100f / count;
            return Enumerable.Repeat(percentage, count).ToArray();
        }

        // 切换视频的“放大/缩小”状态
        private void ToggleVideoExpand(Panel videoContainer, Button expandButton)
        {
            bool isExpanded = expandButton.Text == "缩小";

            if (isExpanded)
            {
                // 缩小逻辑
                videoPanel.RowStyles.Clear();
                videoPanel.ColumnStyles.Clear();
                this.recordPanel.Visible = true;
                int videoCount = videoPanel.Controls.Count;
                if (videoCount == 2)
                {
                    // 如果视频数量为 2，恢复到单行两列布局
                    videoPanel.RowCount = 1;
                    videoPanel.ColumnCount = 2;

                    videoPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100f));
                    videoPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50f));
                    videoPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50f));
                }
                else
                {
                    // 恢复为网格布局
                    int rows = (int)Math.Ceiling(Math.Sqrt(videoCount));
                    int cols = (int)Math.Ceiling((double)videoCount / rows);

                    videoPanel.RowCount = rows;
                    videoPanel.ColumnCount = cols;

                    for (int i = 0; i < rows; i++)
                        videoPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / rows));
                    for (int j = 0; j < cols; j++)
                        videoPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / cols));
                }
                expandButton.Text = "放大"; // 切换按钮文本
                // 恢复所有视频的布局
                foreach (Control control in videoPanel.Controls)
                {
                    control.Visible = true; // 显示所有视频
                }
            }
            else
            {
                // 放大逻辑
                foreach (Control control in videoPanel.Controls)
                {
                    control.Visible = control == videoContainer; // 仅显示当前视频
                }
                this.recordPanel.Visible = false;
                videoPanel.RowStyles.Clear();
                videoPanel.ColumnStyles.Clear();
                videoPanel.RowCount = 1;
                videoPanel.ColumnCount = 1;
                videoPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100f));
                videoPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f));
                expandButton.Text = "缩小"; // 切换按钮文本
            }
        }
        private void ClearRecords(object sender, EventArgs e)
        {
            this.recordListView.Controls.Clear();
            noRecordsLabel.Visible = true;
            recordListView.Visible = false;
            MessageBox.Show("清除完成！");
        }
        private void UpdateApp(object sender, EventArgs e)
        {
            this.showUpdate();
        }
        private void CloseLockScreen(object sender, EventArgs e)
        {
            this.Hide();
            Form1 form1 = Form1.getInstance();
            form1.Show();
        }
        private void ChangeFontSize(int size)
        {
            // 修改整个窗体的字体大小
            ChangeControlFont(recordPanel, size);
            ChangeControlFont(menuStrip, size);
            ChangeControlFont(videoPanel, size);
            this.FontSize = size;
            this.RefreshVideo(null, null); 
        }
        private void ChangeControlFont(Control control, int size)
        {
            // 遍历所有控件，修改字体大小
            control.Font = new Font(control.Font.FontFamily, size);
            //如果control是按钮，则更新按钮尺寸
            if (control is Button button)
            {
                Dictionary<int, int> width= new Dictionary<int, int> {
                    {FontSizeMini,45},
                    {FontSizeSmall, 50},
                    {FontSizeMedium, 60},
                    {FontSizeLarge, 65}
                };
                Dictionary<int, int> height = new Dictionary<int, int> {
                    {FontSizeMini,25},
                    {FontSizeSmall, 25},
                    {FontSizeMedium, 30},
                    {FontSizeLarge, 30}
                };
                button.Size = new Size(width[size], height[size]);
            }
            if (control.Name.Equals("buttonPanel") || control.Name.Equals("recordTitle"))
            {
                if (size == FontSizeMini || size == FontSizeSmall)
                {
                    control.Height = 30;
                }
                else {
                    control.Height = 35;
                }   
            }
            foreach (Control child in control.Controls)
            {
                ChangeControlFont(child, size);
            }
        }

        private void SetRecordPanelDock(DockStyle dockStyle)
        {
            // 更新 recordPanel 的 Dock 属性
            recordPanel.Dock = dockStyle;
            // 根据 recordPanel 的位置调整 Splitter 的 Dock 属性
            switch (dockStyle)
            {
                case DockStyle.Top:
                    splitter.Dock = DockStyle.Top;
                    splitter.Height = 3; // 设置分隔条的高度
                    splitter.Width = this.ClientSize.Width; // 确保宽度覆盖整个窗体
                    recordPanel.Height = 280;
                    recordPanel.Width = this.ClientSize.Width;
                    recordPanel.Padding = new Padding(3, 3, 3, 0);
                    break;

                case DockStyle.Bottom:
                    splitter.Dock = DockStyle.Bottom;
                    splitter.Height = 3; // 设置分隔条的高度
                    splitter.Width = this.ClientSize.Width;
                    recordPanel.Height = 280;
                    recordPanel.Width = this.ClientSize.Width;
                    recordPanel.Padding = new Padding(3, 0, 3, 3);
                    break;

                case DockStyle.Left:
                    splitter.Dock = DockStyle.Left;
                    splitter.Width = 3; // 设置分隔条的宽度
                    splitter.Height = this.ClientSize.Height; // 确保高度覆盖整个窗体
                    recordPanel.Width = 350;
                    recordPanel.Height = this.ClientSize.Height;
                    recordPanel.Padding = new Padding(0, 3, 3, 3);
                    break;

                case DockStyle.Right:
                    splitter.Dock = DockStyle.Right;
                    splitter.Width = 3; // 设置分隔条的宽度
                    splitter.Height = this.ClientSize.Height;
                    recordPanel.Width = 350;
                    recordPanel.Height = this.ClientSize.Height;
                    recordPanel.Padding = new Padding(3, 3, 0, 3);
                    break;
            }
            this.RefreshVideo(null, null);
        }
    }
}
